const { ApiController } = require('jax')

class Controller extends ApiController {
  get Model() {
    return this.ctx.model.Module
  }

  // 分类树
  async tree() {
    const { ctx } = this
    const filter = this.getFilter()

    const returnData = await this.Model.tree({
      filter,
      sort: {
        isTop: 'DESC',
        rank: 'ASC',
      },
    })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }

  // 获取查询条件
  getFilter() {
    const { ctx } = this
    const { query, helper } = ctx
    const { admin } = ctx.state
    const filter = {}

    // 匹配搜索
    ;['workspace'].map((key) => {
      if (query[key] && !query[key] == '') filter[key] = query[key]
    })

    return filter
  }

  async afterShow(doc) {
    const { ctx } = this
    if (doc.modelId) {
      doc._doc.model = await ctx.model.Model.findOne({
        _id: doc.modelId,
      })
    }
  }

  // 导入用户
  async import() {
    const { ctx } = this
    const { config } = this
    const { url } = ctx.request.body

    const localFile = config.uploadDir + URL.parse(url).path

    const workSheetsFromFile = xlsx.parse(localFile)
    if (workSheetsFromFile) {
      const data = workSheetsFromFile[0].data
      xlsxToArray(data)
    }

    ctx.body = {
      code: 0,
      msg: '导入成功',
    }
  }
}

function xlsxToArray(data, cb) {
  const arr = []

  const keys = data[0]
  data.map((item, index) => {
    if (index == 0) return
    const newItem = {}

    item.map((value, index) => {
      const label = keys[index]
      newItem[label] = value
    })

    if (cb) cb(newItem)
    arr.push(newItem)
  })

  return arr
}

module.exports = Controller
